package com.stylefeng.guns.modular.vpn.utils;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @Description Excel数据的导入导出
 * @Author Mr.God
 * @Date 2020-03-09 13:43
 **/
public class PoiExcelUtil {
    /**
     * 写入文件并将文件已二进制流的方式返回为调用者
     * @param response
     * @param workbook
     * @param fileName
     */
    public static void writeWorkBook(HttpServletResponse response,HSSFWorkbook workbook,String fileName){
        //清空response
        response.reset();
        //设置response的header
        response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
        try {
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输入流中
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setSheetColumnWidth(int colCount,HSSFSheet sheet){
        //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度
        for (int i=0;i<colCount;i++){
            sheet.setColumnWidth(i, 20*256);
        }
    }

    /**
     * 设置订单表导出表格的头部信息
     * @param workbook
     * @param sheet
     * @param columns
     */
    public static void setTableHeader(HSSFWorkbook workbook, HSSFSheet sheet,List<String> columns){
        HSSFRow row = sheet.createRow(0);
        setSheetColumnWidth(columns.size(),sheet);

        //设置为居中加粗
        HSSFCellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);

        HSSFCell cell;
        int len = columns.size();
        for (int i = 0;i<len;i++){
            cell = row.createCell(i);
            cell.setCellValue(columns.get(i));
            cell.setCellStyle(style);
        }
    }
}
